package cs;

import java.io.*;
import java.net.*;

public class NbTalkServer {
    public static void main(String[] args) {
        try {
            ServerSocket st=new ServerSocket(8888);
            System.out.println("服务器启动了");
            while(true){
                Socket s=st.accept();
                new TalkerThread(s).start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }


    }
}

class TalkerThread extends  Thread{
    private Socket s;
    public TalkerThread(Socket s){
        this.s=s;
    }

    @Override
    public void run() {
        System.out.println("ip:" + s.getInetAddress() + ",端口:" + s.getPort() + ",本地端口:" + s.getLocalPort());
        try {
            InputStream in = s.getInputStream();
            OutputStream out = s.getOutputStream();
            //接收文本
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            PrintWriter pw = new PrintWriter(out, true);//自动刷新
            String str=null;
            while(true){
                str=br.readLine();
                System.out.println("客户端说:"+str);
                pw.println("你刚才说的:["+str+"]朕知道了");
                if(str.equals("exit"))
                    break;
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(s!=null&&s.isClosed()==false) {
                try {
                    s.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}